<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2020 All rights reserved.
// +----------------------------------------------------------------------
// | User: Simony <1362229026@qq.com>
// | wechat: Shen86579595
// +----------------------------------------------------------------------

namespace app\common\logic;

use alipay\aop\AopClient;
use alipay\aop\request\AlipayTradeAppPayRequest;
use alipay\aop\request\AlipayTradeQueryRequest;
use alipay\aop\request\AlipayFundTransToaccountTransferRequest;


class AppAliPayLogic
{

    public $appId;
    public $rsaPrivateKey;
    public $alipayrsaPublicKey;
    public $notify_url = '121';
    public $gatewayUrl = 'https://openapi.alipay.com/gateway.do';
    public $apiVersion = '1.0';
    public $postCharset = 'utf-8';
    public $format = 'json';
    public $signType;


    public function __construct($config = [])
    {
        //get params
        if (empty($config)) {
            $alipayConfig = sysConfig('alipay');
        } else {
            $alipayConfig = $config;
        }

        $this->rsaPrivateKey = isset($alipayConfig['private_key']) ? trim(file_get_contents(ROOT_PATH . $alipayConfig['private_key'])) : '';
        $this->alipayrsaPublicKey = isset($alipayConfig['public_key']) ? trim(file_get_contents(ROOT_PATH . $alipayConfig['public_key'])) : '';
        $this->signType = isset($alipayConfig['sign_type']) ? $alipayConfig['sign_type'] : '';
        $this->appId = isset($alipayConfig['app_id']) ? $alipayConfig['app_id'] : '';

    }


    /**
     * User: Simony
     * Function:
     * @param $order_id
     * @param $goods_name
     * @param $price
     * @param int $attach
     */
    public function unifiedorder($out_trade_no, $goods_name, $price, $attach = 1)
    {
        $aop = new AopClient();
        //设置公共参数
        $aop->gatewayUrl = $this->gatewayUrl;
        $aop->appId = $this->appId;
        $aop->rsaPrivateKey = $this->rsaPrivateKey; //应用私钥
        $aop->alipayrsaPublicKey = $this->alipayrsaPublicKey; //你的支付宝公钥
        $aop->apiVersion = $this->apiVersion;
        $aop->signType = $this->signType;
        $aop->postCharset = $this->postCharset;
        $aop->format = $this->format;

        $request = new AlipayTradeAppPayRequest();
        $notify_url = config('app.alipay.pay.notify_url');
        $request->setNotifyUrl($notify_url);
        $param['body'] = $goods_name;
        $param['subject'] = $goods_name;
        $param['out_trade_no'] = $out_trade_no;
        $param['total_amount'] = floatval($price);

        $request->setBizContent(json_encode($param));

        $config['sign'] = $aop->sdkExecute($request);
        $config['pay_desc'] = '支付宝支付';
        $config['order_sn'] = $out_trade_no;
        $config['payment_price'] = $price;

        return ds_arr(SUCCESS, '成功', $config);
    }


    /**
     * User: Simony
     * Function:回调校验
     * @param $param
     * @return bool
     */
    public function notifyCheck($param)
    {
        $aop = new AopClient();
        $aop->gatewayUrl = $this->gatewayUrl;
        $aop->appId = $this->appId;
        $aop->rsaPrivateKey = $this->rsaPrivateKey; //应用私钥
        $aop->alipayrsaPublicKey = $this->alipayrsaPublicKey; //你的支付宝公钥
        $aop->apiVersion = $this->apiVersion;
//        $aop->signType = $this->signType;
        $aop->postCharset = $this->postCharset;
        $aop->format = $this->format;
        return $aop->rsaCheckV1($param, null, $this->signType);
    }


    /**
     * User: Simony
     * Function: 查询订单状态
     * @param $out_trade_no
     * @return mixed
     */
    public function queryOrder($out_trade_no)
    {

        $aop = new AopClient();
        //设置公共参数
        $aop->gatewayUrl = $this->gatewayUrl;
        $aop->appId = $this->appId;
        $aop->rsaPrivateKey = $this->rsaPrivateKey; //应用私钥
        $aop->alipayrsaPublicKey = $this->alipayrsaPublicKey; //你的支付宝公钥
        $aop->apiVersion = $this->apiVersion;
        $aop->signType = $this->signType;
        $aop->postCharset = $this->postCharset;
        $aop->format = $this->format;

        $request = new AlipayTradeQueryRequest();

        $param['out_trade_no'] = $out_trade_no;
        $param['trade_no'] = '';

        $request->setBizContent(json_encode($param));

        $result = $aop->execute($request);

        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $data = json_decode(json_encode($result->$responseNode), true);

        $msg = isset($data['sub_msg']) ? $data['sub_msg'] : $data['msg'];
        if ($data['code'] != 10000) return ds_arr(ERROR, $msg);

        $res = [
            'total_fee' => $data['total_amount'],
            'out_trade_no' => $data['out_trade_no'],
            'trade_state' => $data['trade_status'],
            'trade_state_desc' => '',
        ];
        return ds_arr(SUCCESS, '查询成功', $res);

    }


    /**
     * User: Simony
     * Function:
     */
    public function singleTransfer($out_biz_no, $account, $account_name, $price)
    {
        $aop = new AopClient();
        //设置公共参数
        $aop->gatewayUrl = $this->gatewayUrl;
        $aop->appId = '2021001182639135';
        $aop->rsaPrivateKey = 'MIIEowIBAAKCAQEAmXRU2V4KouOFFW7qf5LoYfhi8GcHr3O+2VZGsslrnbl1MHQmi/XDCGDxdjriUuTtlxXwdBcLzkknzJCcV31GdkwgsXFn7cgNfXf7EXeX5duA5H7w5jU0SBIivPNCDbLzYMFNTkKc2C4YXW/VwOCZ6pUuImID8tGkaXuCGblDxH5qxKCRpZUYs+8Vjd3D7X1AE36Nqp5pInpcJrhCV0qweC2ebwXzt2B3SzOM9gukD2DRgGB8Cz78A3YIjNTmROUqQCR7jewnmWiD6j25bOT8I4oQLwLwJ243FqgscwRN6uIwKIxruDWSrXf9bWJH21Sdwh36Y1KX25MXFVxgzsinKwIDAQABAoIBADpxk981cdeXz5faJnVv/hFSCFyG4OZxrr4XndV54QKxH3DUy9mCQEVwpoXg51Gq3tIsCOgt3tEyC3ZdnS21CKEFXW43Qt3M01Z126lLYw6oCu77acRDfyXzwkc0XnPZM9glxsuHkzTCWYU8kqxi3jv5lRiDO/2+2l9SKrqhVK4A4IMXSpuSoiyr/6GW+IETsr0W2OodkPshuGaZqe/Xa+t6v6TPC6kMGvBhuFAlnJ54BJiS5GRVixP813pT3TvLLhQsJhS+zxpZ6oaG18JDTH40bsmkgYCyXCvIvqohorWofnFbc7E/Qo85W296XOvQ8DF6KKsaQb00DGikZxPe9AECgYEAz+6AiufQlcXKNNVYvxWtsv12O2lBGKVILzg89RICgKobumxJys4Gz70me61YlJQnTSH6EJ0wskci1EwK1+MC1mTtvJxoOVbJQ0A78gk6B+AiT+GWmkuw+Mw736SROEwu7twyZ2G7Cfr/70mRHXLoZPN4zMoTvRqua/A5Z2Qbdw8CgYEAvO3XBjg3aAZJLr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2UG403NEaD1UQQIDAQAB'; //你的支付宝公钥
        $aop->apiVersion = $this->apiVersion;
        $aop->signType = $this->signType;
        $aop->postCharset = $this->postCharset;
        $aop->format = $this->format;

        $param['out_biz_no'] = $out_biz_no;
        $param['payee_type'] = 'ALIPAY_LOGONID';
        $param['payee_account'] = $account;
        $param['payee_real_name'] = $account_name;
        $param['amount'] = $price;
        $param['remark'] = '提现订单号：' . $out_biz_no;

        $request = new AlipayFundTransToaccountTransferRequest();
        $request->setBizContent(json_encode($param));
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $data = json_decode(json_encode($result->$responseNode), true);

        $msg = isset($data['sub_msg']) ? $data['sub_msg'] : $data['msg'];
        if ($data['code'] != 10000) return ds_arr(ERROR, $msg);

        return ds_arr(SUCCESS, '查询成功', $data);

    }

}
